<?php
/**
 * (ajax)
 */
namespace App\Admin\Ajax\Basics;

use App\Logic\Amazon\Api\Authorize;
use App\Models\Basics\AmazonAccount;
class AmazonAccountAjax {

    /**
     * 授权账号
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function doOauth($id){
        try{
            $model = AmazonAccount::query()->findOrFail($id);
            if($model->status != 1){
                return response()->json(['status' => false, 'message' => '状态有误！']);
            }
            if($model->auth_status == 1 && $model->refresh_token && $model->auth_at){
                $authAtExpired = strtotime($model->auth_at) - strtotime('-1 year');
                if($authAtExpired > AmazonAccount::AUTH_AT_EXPIRED){
                    return response()->json(['status' => false, 'message' => '已授权！']);
                }
            }
            $accountCountry = $model->account_country->sortBy('url_order')->first();
            if(!$accountCountry){
                return response()->json(['status' => false, 'message' => '该账号没有设置对应国家！']);
            }
            $sellerCentralUrl = $accountCountry->seller_central_url ?: '';
            if(!$sellerCentralUrl){
                return response()->json(['status' => false, 'message' => '该账号对应的国家没有设置商城URL！']);
            }
            $authorize = new Authorize();
            $oauthUrl = $authorize->getOauthUrl($sellerCentralUrl,$id);
            return response()->json(['status' => true, 'message' => '操作成功！', 'oauth_url' => $oauthUrl]);
        }catch (\Exception $e){
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }
}
